package com.example.mqdemo.rabbit;

import com.example.mqdemo.common.ExchangeConstant;
import com.example.mqdemo.common.QueueConstant;
import com.example.mqdemo.common.RoutingConstant;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * rabbitmq队列配置
 */
@Configuration
public class QueueConfig {

    /**
     * 死信队列 交换机标识符
     */
    private static final String DEAD_LETTER_EXCHANGE_KEY = "x-dead-letter-exchange";

    /**
     * 死信队列交换机绑定键标识符
     */
    private static final String DEAD_LETTER_ROUTING_KEY = "x-dead-letter-routing-key";

    /**
     * 死信队列里面消息的超时时间
     */
    private static final String X_MESSAGE_TTL = "x-message-ttl";

    @Bean(QueueConstant.orderQueueName)
    public Queue orderQueue() {
        return QueueBuilder.durable(QueueConstant.orderQueueName).build();
    }

    /**
     * 取消订单死信队列
     *
     * @return
     */
    @Bean(QueueConstant.orderCancelDeadQueueName)
    public Queue orderCancelDeadQueue() {
        Map<String, Object> args = new HashMap<>(2);
        // x-dead-letter-exchange 声明 死信交换机
        args.put(DEAD_LETTER_EXCHANGE_KEY, ExchangeConstant.orderCancelChangeName);
        //x-dead-letter-routing-key 声明 死信路由键
        args.put(DEAD_LETTER_ROUTING_KEY, RoutingConstant.orderCancelRoutingKey);
        //在队列中延迟30s后，消息重新投递到x-dead-letter-exchage对应的队列中,routingkey是自己配置的
//        args.put(X_MESSAGE_TTL, 30 * 1000);
        // 针对Queue设置x-expires(到期删除队列) 或者 针对Message设置 x-message-ttl，来控制消息的生存时间，如果超时(两者同时设置以最先到期的时间为准)，则消息变为dead letter(死信)
        return QueueBuilder.durable(QueueConstant.orderCancelDeadQueueName).ttl(15 * 1000).withArguments(args).build();
    }

    /**
     * 取消订单死信队列
     *
     * @return
     */
    @Bean(QueueConstant.orderCancelQueueName)
    public Queue orderCancelQueue() {
        return QueueBuilder.durable(QueueConstant.orderCancelQueueName).build();
    }
}
